// utils/request.js

const BASE_URL = 'http://www.zqy.cn:6868'; // 后端接口地址
let isRefreshing = false;

function request({ url, method = 'GET', data = {}, showLoading = true }) {
  const token = wx.getStorageSync('token') || '';
  const header = {
    'Content-Type': 'application/json',
  };
  console.log(`发起请求: ${method} ${BASE_URL + url}`, data);
  if (token) {
    header['Authorization'] = `Bearer ${token}`;
  }

  if (showLoading) {
    wx.showLoading({ title: '加载中...', mask: true });
  }

  return new Promise((resolve) => {
    wx.request({
      url: BASE_URL + url,
      method,
      data,
      header,
      timeout: 30000, // 设置超时时间为 30 秒
      success: (res) => {
        if (res.statusCode === 200) {
          const { code, message, data } = res.data;
          if (code === 2000) {
            if (showLoading) {
              wx.hideLoading();
            }
            resolve(res.data);
          } else if (code === 4030) {
            // handleTokenExpired();
            if (showLoading) {
              wx.hideLoading();
            }
            wx.showModal({
              title: '登陆失败',
              content: message || '请求失败',
              showCancel: false,
              confirmText: '知道了',
            });
            resolve(null);
          } else {
            // 确保在显示模态框前隐藏 loading
            if (showLoading) {
              wx.hideLoading();
            }
            console.log('进入非 2000 code 处理分支');
            wx.showModal({
              title: '异常提示',
              content: message || '请求失败',
              showCancel: false,
              confirmText: '知道了',
              success: (res) => {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              },
              fail: (err) => {
                console.error('wx.showModal 调用失败:', err);
              }
            });
            resolve(null);
          }
        } else {
          if (showLoading) {
            wx.hideLoading();
          }
          wx.showToast({
            title: '服务器错误',
            icon: 'none',
            duration: 2000
          });
          resolve(null);
        }
      },
      fail: (err) => {
        console.log('请求失败:', BASE_URL + url, err);
        if (showLoading) {
          wx.hideLoading();
        }
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000
        });
        resolve(null);
      }
    });
  });
}

function handleTokenExpired() {
  if (isRefreshing) return;
  isRefreshing = true;

  wx.removeStorageSync('token');
  wx.showToast({
    title: '登录已过期，请重新登录',
    icon: 'none',
    duration: 2000
  });

  setTimeout(() => {
    wx.reLaunch({
      url: '/page/component/login/index'
    });
    isRefreshing = false;
  }, 1500);
}

module.exports = {
  request
};
